package com.smashcrush.client.gwt.manager;

import java.util.List;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smashcrush.client.gwt.SecurityContext;
import com.smashcrush.client.gwt.service.ScriptServiceAsync;
import com.smashcrush.model.Script;

public class ScriptsManager {

	static ScriptsManager manager = new ScriptsManager();

	List<Script> scripts;

	public static ScriptsManager get() {
		return manager;
	}

	public List<Script> getScripts() {
		return scripts;
	}

	public void saveScript(final Script script) {
		
		ScriptServiceAsync.RPC.get().saveScript(
				SecurityContext.get().getToken(), script,
				new AsyncCallback<String>() {

					@Override
					public void onSuccess(String result) {

						if (script.getId() == null) {
							script.setId(result);
							scripts.add(script);
						}

						Window.alert("Saved!");
					}

					@Override
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}
				});
	}

	public void loadData(final Command onLoad) {
		ScriptServiceAsync.RPC.get().getScripts(
				SecurityContext.get().getToken(),
				new AsyncCallback<List<Script>>() {

					@Override
					public void onSuccess(List<Script> result) {
						scripts = result;

						onLoad.execute();
					}

					@Override
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}
				});
	}

}
